import React, { Component } from 'react';

class Index extends Component {
    constructor(props) {
        super(props);
        this.state = {
            msg: "",
            list: []
        }
    }

    render() {
        const ListItem = this.state.list.map((item, index) => {
            return (
                <div key={item}>
                    <span>{index + 1}</span>{item}
                    <button onClick={this.handleDelete.bind(this, index)}>删除</button>
                </div>
            )
        })
        return (
            <div>
                <h1>todo</h1>
                <input type="text" value={this.state.msg} onChange={this.handleChange} onKeyUp={this.handleEnter} />
                <div>{ListItem}</div>
            </div>
        );
    }
    handleChange = (event) => {
        // console.log(event.target.value);
        this.setState({
            msg: event.target.value
        })
    }
    handleEnter = (event) => {
        if (event.keyCode === 13) {
            // console.log(this.state.msg);
            let list = this.state.list;
            list.push(this.state.msg);
            this.setState({
                list,
                msg: ""
            })
        }
    }
    handleDelete(index) {
        let list = this.state.list;
        list.splice(index, 1);
        this.setState({
            list
        })
    }
}

export default Index;
